package urlencoderanddecoder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLEncoderAndDecoder {
	/**
	 * 用指定的编码集定的字符串，该字符串是url中需要编码的一个部分
	 * @param urlPart
	 * @return
	 */
	public static String encode(String urlPart, String charsetName) {
		String encoded = null;
		try {
			encoded = URLEncoder.encode(urlPart, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encoded;
	} 
	
	/**
	 * 用utf-8编码指定的字符串，该字符串是url中需要编码的一个部分
	 * @param urlPart
	 * @return
	 */
	public static String encode(String urlPart) {
		return encode(urlPart, "utf-8");
	}
	
	public static String decode(String url, String charsetName) {
		String decoded = null;
		try {
			decoded = URLDecoder.decode(url, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return decoded;
	}
	
	public static String decode(String url) {
		return decode(url, "utf-8");
	}
}
